package ipmsg.etc;

import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.StringTokenizer;

import com.czh.www.HexDataUtils;

/**
 * 
 * @author idcomcn
 *
 */
public class Command {
	/** 版本 **/
	private int version;
	/** 包编号 **/
	private int packetNo;
	/** 发送者姓名 **/
	private String senderName = null;
	/** 发送者主机名 **/
	private String senderHost = null;
	/** 命令字 **/
	private int flag;
	/** 附加信息 **/
	private String additional = null;
	/** 附加信息Hex) **/
	private String additionalHex = null;

	private String ip = null;

	public Command() {
	}

	public Command(int flag) {
		this.flag = flag;
		this.packetNo = ((int) new Date().getTime());
		this.version = 1;
		this.senderName = GlobalVar.USER_NAME;
		this.senderHost = GlobalVar.HOST_NAME;
	}

	public String getIp() {
		return this.ip;
	}

	public int getFlag() {
		return this.flag;
	}

	public String getAdditional() {
		return this.additional;
	}

	public int getPacketNo() {
		return this.packetNo;
	}

	public String getSenderHost() {
		return this.senderHost;
	}

	public String getSenderName() {
		return this.senderName;
	}

	public int getVersion() {
		return this.version;
	}

	public boolean setAdditional(String additional) {
		if ((additional == null) || (additional.equals("")) || (additional.length() > 1000)) {

			this.additional = null;
			return false;
		}
		this.additional = additional;
		return true;
	}

	public boolean setSenderHost(String senderHost) {
		if ((senderHost == null) || (senderHost.equals("")) || (senderHost.length() > 50)) {

			this.senderHost = null;
			return false;
		}
		this.senderHost = senderHost;
		return true;
	}

	public boolean setSenderName(String senderName) {
		if ((senderName == null) || (senderName.equals("")) || (senderName.length() > 50)) {

			this.senderName = null;
			return false;
		}
		this.senderName = senderName;
		return true;
	}

	public void setVersion(int version) {
		this.version = version;
	}

	public void setVersion(String version) {
		setVersion(UtilityGlobal.atoi(version));
	}

	public void setPacketNo(int packetNo) {
		this.packetNo = packetNo;
	}

	public boolean setPacketNo(String packetNo) {
		try {
			setPacketNo(Integer.parseInt(packetNo));
			return true;
		} catch (NumberFormatException e) {
		}
		return false;
	}

	public void setFlag(int flag) {
		this.flag |= flag;
	}

	public void resetFlag(int flag) {
		this.flag = flag;
	}

	public boolean setFlag(String flag) {
		try {
			setFlag(Integer.parseInt(flag));
			return true;
		} catch (NumberFormatException e) {
		}
		return false;
	}

	public boolean setIp(String ip) {
		if (UtilityGlobal.isIP(ip)) {
			this.ip = ip;
			return true;
		}
		return false;
	}

	public String getAdditionalHex() {
		return additionalHex;
	}

	public void setAdditionalHex(String additionalHex) {
		this.additionalHex = additionalHex;
	}

	public byte[] exportToBuf() {
		try {
			return (this.version + ":" + this.packetNo + ":" + this.senderName.replaceAll(":", "_") + ":"
					+ this.senderHost.replaceAll(":", "_") + ":" + this.flag + ":" + this.additional + '\000')
							.getBytes(GlobalVar.CHARACTER_ENCODING);
		} catch (UnsupportedEncodingException ex) {
		}

		return null;
	}

	public static Command createCommand(byte[] buf, String ip) {
		if ((buf == null) || (ip == null)) {
			return null;
		} // end if

		System.out.println("idcomcn,hex:" + HexDataUtils.hexDataAddSpace(HexDataUtils.bytes2HexData(buf)));

		// 1:1511702509:Administrator:PFIX7GMHQUEOJ9F:1049376:1:1511119980:Administrator:PFIX7GMHQUEOJ9F:0:.1:1511119983:Administrator:PFIX7GMHQUEOJ9F:6291457:Administrator..
		String tmpCom;
		try {
			tmpCom = new String(buf, GlobalVar.CHARACTER_ENCODING);
		} catch (UnsupportedEncodingException ex) {
			return null;
		}

		System.out.println("idcomcn,tmpCom:" + tmpCom);

		Command cmd = new Command();

		List<String> list = msgSplit(tmpCom, ":");
		if (list.size() < 6) {
			return null;
		} // end if

		cmd.setVersion(list.get(0));
		cmd.setPacketNo(list.get(1));
		cmd.setSenderName(list.get(2));
		cmd.setSenderHost(list.get(3));
		cmd.setFlag(list.get(4));

		// 获取扩展的附加信息hex
		byte byDelim = 0x3A;
		List<Integer> listIndex = getListIndex(buf, byDelim);
		byte[] bys = getByteArr(buf, listIndex.get(4) + 1, buf.length);
		cmd.setAdditionalHex(HexDataUtils.bytes2HexData(bys));

		String additional = null;
		try {
			additional = new String(bys, GlobalVar.CHARACTER_ENCODING);
		} catch (UnsupportedEncodingException e) {
		} // end if
		cmd.setAdditional(additional);

		cmd.ip = ip;
		return cmd;
	}

	public String show() {
		StringBuilder sb = new StringBuilder();
		sb.append("开始").append("\n");
		sb.append("version : " + getVersion()).append("\n");
		sb.append("packetNo : " + getPacketNo()).append("\n");
		sb.append("senderName : " + getSenderName()).append("\n");
		sb.append("senderHost : " + getSenderHost()).append("\n");
		sb.append("flag : " + getFlag()).append("\n");
		sb.append("addtional : " + getAdditional()).append("\n");
		sb.append("addtionalHex : " + getAdditionalHex()).append("\n");
		sb.append("ip : " + getIp()).append("\n");
		return sb.toString();
	}

	@Override
	public String toString() {
		return show();
	}

	/**
	 * 获取分割字符串的索引
	 * 
	 * @param buf
	 * @param delim
	 * @return
	 */
	public static List<Integer> getListIndex(byte[] buf, byte byDelim) {
		List<Integer> listIndex = new ArrayList<Integer>();
		if (null == buf || buf.length == 0) {
			return listIndex;
		} // end if

		for (int i = 0; i < buf.length; i++) {
			if (buf[i] == byDelim) {
				listIndex.add(i);
			} // end if
		} // end for

		return listIndex;
	}

	/**
	 * 分割字符串
	 * 
	 * @param msg
	 * @param delim
	 * @return
	 */
	public static List<String> msgSplit(String msg, String delim) {
		List<String> list = new ArrayList<String>();
		if (null == msg) {
			return list;
		} // end if
		StringTokenizer st = new StringTokenizer(msg, delim);
		while (st.hasMoreTokens()) {
			list.add(st.nextToken());
		} // end while
		return list;
	}

	/**
	 * 从byte[]中抽取新的byte[]
	 * 
	 * @param data
	 *            - 元数据
	 * @param start
	 *            - 开始位置
	 * @param end
	 *            - 结束位置
	 * @return 新byte[]
	 */
	public static byte[] getByteArr(byte[] data, int start, int end) {
		byte[] ret = new byte[end - start];
		for (int i = 0; (start + i) < end; i++) {
			ret[i] = data[start + i];
		}
		return ret;
	}

	// public static void main(String[] args) {
	// byte[] bys = { 0x11, 0x3a, 0x12, 0x32, 0x3a, 0x12, 0x23, 0x3a, 0x22, 0x31 };
	// // String bufHex = HexDataUtils.Bytes2HexData(bys);
	// // List<String> strs = msgSplit(bufHex, "3A");
	// // List<String> strs = msgSplit(bys, ":");
	// String str =
	// HexDataUtils.hexDataAddSpace(HexDataUtils.bytes2HexData(getByteArr(bys, 1 +
	// 1, bys.length)));
	// System.out.println(str);
	// }

}
